__all__ = ('__version__', 'Factory', 'mTokenError', 'mCheckError')
__version__ = '0.0.0-draft'

from Exceptions import *
from Abstract import Container

class Rules (Container):
	from Actions import IPTables, Pass, Drop, Reject, Rewrite
	Children = (IPTables, Pass, Drop, Reject, Rewrite)

	def __init__ (self, Filename, LineNo):
		super (Rules, self).__init__ (Filename, LineNo)
		self.Rules = []

	def __str__ (self):
		return '\n'.join (str (Rule) for Rule in self.Rules)

	def commit (self):
		if self.Current is None:
			return None
		self.commitCurrent ()
		self.Rules.append (self.Current)
		self.Current = None

	def render (self):
		return '\n'.join (Rule.render () for Rule in self.Rules)
# ----------------------------------------------------------------------------

def Factory (Filename):
	from shlex import shlex
	if Filename and Filename != '-':
		try:
			shlex = shlex (open (Filename), Filename, True)
		except IOError as X:
			raise mParseError (str (X))
	else:
		shlex = shlex (posix=True)
	shlex.whitespace_split = True
	R = Rules (None, None)
	while True:
		try:
			RawToken = shlex.get_token ()
		except ValueError as X:
			raise mTokenError (str (X), shlex.infile, shlex.lineno)
		if RawToken is None:
			R.commit ()
			break
		Token = RawToken.lower ()
		Test = R.token (shlex.infile, shlex.lineno, Token, RawToken)
		if not Test:
			raise mTokenError ("Unknown or misplaced instruction '%s'" % Token, shlex.infile, shlex.lineno)
	return R
# ----------------------------------------------------------------------------
